//
//  JCHomeTableViewController.swift
//  SinaWeibo_18
//
//  Created by mac on 15/10/9.
//  Copyright © 2015年 cz. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class JCHomeTableViewController: UITableViewController, JCPopViewDelegate {
    //遮罩
    var popView: JCPopView?
    
    //定义可变数组,存储数据
    lazy var statusArray: [JCStatusFrame] = [JCStatusFrame]()
    
    let reuseID = "homeCell_id"
    override func viewDidLoad() {
        super.viewDidLoad()
        //设置首页导航栏
        setNavItem()
//        //请求数据
//        loadData()
        //创建重用cell , 设置上下拉控件
        setupTableView()
        
        //设置标记个数
        self.tabBarItem.badgeValue = "10"
        
        
    }
    // MARK: - 设置导航栏item内容
    private func setNavItem(){
        navigationItem.rightBarButtonItem = UIBarButtonItem.item("navigationbar_pop", target: self, action: "push")
        navigationItem.leftBarButtonItem = UIBarButtonItem.item("navigationbar_friendsearch", target: self, action: "push")
        //设置顶部的标题按钮
        setTitleButton()
        
    }
    // MARK: - 导航栏的点击事件
    @objc private func push(){
//        let vc = JCTempViewController()
//        navigationController?.pushViewController(vc, animated: true)
        
        //设置badgeValue为空
        tabBarItem.badgeValue = nil
    }
    // MARK: - 设置顶部的标题按钮
   private func setTitleButton(){
        let button = JCHomeTitleButton()
        //添加监听 //顶部标题按钮的点击事件
    button.addTarget(self, action: "titleBtnDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
    //设置btn 属性
//    button.backgroundColor = UIColor.redColor()
    
    button.setTitle(JCUserAccount.loadUserAccount()?.screen_name ?? "首页", forState: UIControlState.Normal)
    button.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
    button.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Selected)
    
    button.setTitleColor(RGB(r: 80, g: 80, b: 80), forState: UIControlState.Normal)
    button.sizeToFit()
    
    navigationItem.titleView = button
    }
    
    // MARK: - 顶部标题按钮的点击事件
    @objc private func titleBtnDidClick(button: UIButton){
        button.selected = !button.selected
        
        //弹出内容视图(小灰框里面的)
        let contentView = UIButton()
        //内容视图按钮的点击事件
        contentView.addTarget(self, action: "contentViewDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        contentView.setTitle("点我啊", forState: UIControlState.Normal)
        contentView.backgroundColor = UIColor.redColor()
        contentView.size = CGSizeMake(150, 150)
        
        let view = JCPopView(customView: contentView)
        //设置代理
        view.popViewDelegate = self
        view.show(button)
        self.popView = view
    }
    // MARK: - 内容视图按钮的点击事件
    @objc private func contentViewDidClick(){
        self.popView!.dismiss()
        printLog("点击了button,逻辑是:一个大的遮罩view,初始化了一个小灰框imageview,小灰框里添加了一个button(view)")
    }
    
    // MARK: - 实现自定义代理方法
    func popViewWillDismiss() {
        let button = navigationItem.titleView as! UIButton
        button.selected = false
    }
    // MARK: - 设置tableview
    private func setupTableView(){
        //注册cell  使用自定义cell
        self.tableView.registerClass(JCStatusCell.self, forCellReuseIdentifier: reuseID)
        
        //去掉分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        //上拉加载控件
        self.tableView.tableFooterView = pullupView
        
        //下拉刷新控件(系统自带)
        self.refreshControl = UIRefreshControl()
        self.refreshControl?.beginRefreshing()
        //添加监听
        self.refreshControl!.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        //请求数据
        loadData()
    }
    
    // MARK: - 请求数据
    @objc private func loadData(){
        //请求地址
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
        //请求参数
//        var params = [
//            "access_token": JCUserAccount.loadUserAccount()!.access_token!
//        ]
        var params = [String: AnyObject]()
        //添加参数  上拉返回数据
        if pullupView.isAnimating() {
            if let statusFrame = statusArray.last {
                params["max_id"] = "\(statusFrame.status!.id - 1)"
            }
        }else{
            if let statusFrame = statusArray.first{
                params["since_id"] = "\(statusFrame.status!.id)"
            }
        }
        //发送请求
        JCNetWorkTools.request(.GET,url: urlString, params: params, success: { (result) -> () in
           
//            if let resultDic = result as? [String: AnyObject] {
            //请求成功
                //数组里面包含字典
                let statusDics = result["statuses"] as? [[String: AnyObject]]
                //创建临时数组
                var tempArray = [JCStatusFrame]()
                for statusDic in statusDics! {
                    
                    //初始化模型
                    let status = JCStatus(dict: statusDic)
                    //通过数据模型生成frame模型
                    let statusFrame = JCStatusFrame()
                    statusFrame.status = status
                    
                    //添加到可变数组
                    tempArray.append(statusFrame)
                }
                //打印加载的数据个数
                printLog(tempArray.count)
                
                //判断是否是上拉刷新
                if self.pullupView.isAnimating() {
                    //添加到数据存储数组里
                    self.statusArray += tempArray
                }else{
                    self.statusArray = tempArray + self.statusArray
                    
                    //如果是下拉刷新,才提示
                    if  self.statusArray.count != 0 {
                        //显示下拉刷新的提示label
                        self.showPulldownTips(tempArray.count)
                    }
                    
                }
                //刷新数据
                self.tableView.reloadData()
//            }
            //停止菊花转
            self.endRefreshing()
            //            self.pullupView.stopAnimating()
            }) { (error) -> () in  //请求数据失败
                    printLog("错误信息\(error)")
            
                SVProgressHUD.showInfoWithStatus("请求数据失败,请检查网络")
                //               self.pullupView.stopAnimating()
                self.endRefreshing()
        }
        
    }
  
   @objc private func loadData2(){
        //请求地址
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
        //请求参数
        var params = [
            "access_token": JCUserAccount.loadUserAccount()!.access_token!
        ]
        //添加参数  上拉返回数据
        if pullupView.isAnimating() {
            if let statusFrame = statusArray.last {
            params["max_id"] = "\(statusFrame.status!.id - 1)"
            }
        }else{
            if let statusFrame = statusArray.first{
            params["since_id"] = "\(statusFrame.status!.id)"
            }
        }
        
    let manager = AFHTTPSessionManager()
        manager.GET(urlString, parameters: params, success: { (dataTask, result) -> Void in
           // printLog(result)
            if let resultDic = result as? [String: AnyObject] {
                //数组里面包含字典
                let statusDics = resultDic["statuses"] as? [[String: AnyObject]]
                //创建临时数组
                var tempArray = [JCStatusFrame]()
                for statusDic in statusDics! {
                    
                    //初始化模型
                    let status = JCStatus(dict: statusDic)
                    //通过数据模型生成frame模型
                    let statusFrame = JCStatusFrame()
                    statusFrame.status = status
                    
                    //添加到可变数组
                    tempArray.append(statusFrame)
                }
                //打印加载的数据个数
                printLog(tempArray.count)
                
                //判断是否是上拉刷新
                if self.pullupView.isAnimating() {
                     //添加到数据存储数组里
                self.statusArray += tempArray
                }else{
                    self.statusArray = tempArray + self.statusArray
                    
                    //如果是下拉刷新,才提示
                    if  self.statusArray.count != 0 {
                        //显示下拉刷新的提示label
                        self.showPulldownTips(tempArray.count)
                    }

                }
                //刷新数据
                self.tableView.reloadData()
            }
            //停止菊花转
//            self.pullupView.stopAnimating()
            self.endRefreshing()
            }) { (dataTask, error) -> Void in  //请求数据失败
                
                SVProgressHUD.showInfoWithStatus("请求数据失败,请检查网络")
//               self.pullupView.stopAnimating()
                self.endRefreshing()
        }
        
    }
    
    
    
    // MARK: - 结束刷新
    private func endRefreshing(){
        self.pullupView.stopAnimating()
        //下拉控件停止刷新
        self.refreshControl?.endRefreshing()
        
    }
    
    // MARK: - 显示下拉label
    private func showPulldownTips(count: Int){
        
        //若label正在执行动画,返回
        if pulldownLabel.hidden == false {
            return
        }
        
        //判断是否有更新的数据
        pulldownLabel.text = count == 0 ? "没有微博数据" : "\(count)条新微博"
        
        //设置动画
            //显示label
        pulldownLabel.hidden = false
            //位置
        let height: CGFloat = 35
        pulldownLabel.size = CGSizeMake(ScreenWidth, height)
        pulldownLabel.y = CGRectGetMaxY((self.navigationController?.navigationBar.frame)!) - height
        UIView.animateWithDuration(1, animations: { () -> Void in
            //出来
            self.pulldownLabel.transform = CGAffineTransformMakeTranslation(0, height)
            }) { (finish) -> Void in
                //回去
                UIView.animateWithDuration(1, delay: 1, options: [], animations: { () -> Void in
                    //还原
                    self.pulldownLabel.transform = CGAffineTransformIdentity
                    }, completion: { (finish) -> Void in
                        //隐藏label
                        self.pulldownLabel.hidden = true
                })
        }
        
    }
    
    
    // MARK: - 菊花(上拉)加载控件
    private lazy var pullupView: UIActivityIndicatorView = {
        let pullupView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        pullupView.backgroundColor = UIColor.redColor()
        return pullupView
    }()
    
    // MARK: - 下拉刷新提示的label
    private lazy var pulldownLabel: UILabel = {
        let label = UILabel()
        //label属性
        label.backgroundColor = UIColor.orangeColor()
        label.textColor = UIColor.whiteColor()
        label.font = UIFont.systemFontOfSize(14)
        label.textAlignment = NSTextAlignment.Center
        //文字
        label.text = "没有微博数据"
        //添加到nav bar 后面
        self.navigationController!.view.insertSubview(label, belowSubview: self.navigationController!.navigationBar)
        //默认不显示
        label.hidden = true
        return label
    }()
    
}


//维护  数据源和代理
extension JCHomeTableViewController{
    // MARK: - UITableViewDataSource & UITableViewDelegate
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statusArray.count
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseID, forIndexPath: indexPath) as! JCStatusCell
        
        cell.statusFrame = statusArray[indexPath.row]
        
//        let status = self.statusArray[indexPath.row].status!
//        //赋值数据
//        cell.textLabel?.text = status.text
//        //设置图片
//        let url = NSURL(string: status.user!.profile_image_url!)
//        cell.imageView?.sd_setImageWithURL(url)
        //判断是否是最后一条数据,加载更多
        if  indexPath.row == statusArray.count-1 && !pullupView.isAnimating() {
            printLog("下拉加载更多")
            pullupView.startAnimating()
            loadData()
        }
        
        return cell
        
    }
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tabBarItem.badgeValue = "1"
    }
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return self.statusArray[indexPath.row].cellHeight!
    }
}